package com.wuwei.aliocr.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.wuwei.aliocr.domain.LessonRecord;
import com.wuwei.aliocr.domain.Teacher;
import com.wuwei.aliocr.listener.LessonRecordListener;
import com.wuwei.aliocr.listener.LessonRecordDao;
import com.wuwei.aliocr.result.Result;
import com.wuwei.aliocr.service.ExcelService;
import com.wuwei.aliocr.service.LessonRecordService;
import com.wuwei.aliocr.service.PaiKeService;
import com.wuwei.aliocr.service.UploadService;
import com.wuwei.aliocr.utils.CommonUtils;
import com.wuwei.aliocr.vo.PaiKeVo;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value="/paike")
@CrossOrigin
public class PaiKeController {

    @Resource
    private PaiKeService paiKeService;

    @Resource
    private ExcelService excelService;

    @Resource
    private UploadService uploadService;

    @Resource
    private LessonRecordDao lessonRecordDao;

    @Resource
    private LessonRecordService lessonRecordService;

    @GetMapping("paike")
    public Result paike() throws Exception {
        paiKeService.addWorkDay();
        return Result.ok(null);
    }

    //根据已有的工作日规定生成excel表格
    @GetMapping("excel/{subject}/{hours}/{date}/{morningOrAfternoon}")
    public Result excel(@PathVariable("subject") String subject,@PathVariable("hours") Integer hours,@PathVariable("date") String date,@PathVariable("morningOrAfternoon") String setMorningOrAfternoon) throws Exception {
        excelService.getExcel(subject,hours,date,setMorningOrAfternoon);
        return Result.ok(null);
    }

    @GetMapping("excel/{date}/{type}")
    public void excel(@PathVariable("date") String date, @PathVariable("type") String type, HttpServletRequest request, HttpServletResponse  response) throws Exception {
        LocalDate localDate = LocalDate.parse(date);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
        String formattedDate = localDate.format(formatter);
        excelService.writeExcel(formattedDate,type);
        String filePath = "D:/work5.xlsx";

        // 设置响应的内容类型为 Excel
        response.setContentType("application/vnd.ms-excel");

        // 设置响应头，告诉浏览器该文件以附件形式下载
        response.setHeader("Content-Disposition", "attachment; filename=\"work5.xlsx\"");

        try (InputStream inputStream = new FileInputStream(filePath);
             OutputStream outputStream = response.getOutputStream()) {
            // 将 Excel 文件的内容以流的形式写入响应对象
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            // 处理异常
        }
    }

    @PostMapping("excel/upload")
    public Result<String> uploadToSql(@RequestParam("file") MultipartFile file){
        String fileName = file.getOriginalFilename(); // 获取文件名
        String fileType = file.getContentType(); // 获取文件类型
        String workingDir = System.getProperty("user.dir");

        try {
            String savePath = workingDir+"/src/main/java/com/wuwei/aliocr/static/file.xlsx"; // 设置保存文件的路径
            file.transferTo(new File(savePath)); // 保存文件到指定路径

            // 创建 ExcelReader 对象
            ExcelReader excelReader = EasyExcel.read(savePath, LessonRecord.class, new LessonRecordListener(lessonRecordDao)).build();

            // 获取 sheet 数量
            List<ReadSheet> readSheets = excelReader.excelExecutor().sheetList();
            System.out.println("Sheet 数量: " + readSheets.size());
            // 关闭 ExcelReader
            excelReader.finish();

            uploadService.uploadToSql(savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("文件上传成功，已同步到数据库");
    }

    @GetMapping("getpaikeForTheDate/list/{date}")
    public Result<List<LessonRecord>> excel(@PathVariable("date") Date date){
        System.out.println(date);
        System.out.println(date);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // 将日期格式化为目标格式的字符串
        String formattedDate = formatter.format(date);
        List<LessonRecord> list = paiKeService.getPaikeForTheDate(formattedDate);
        return Result.ok(list);
    }

    @Resource
    private CommonUtils commonUtils;

    @PostMapping ("lessonRecord")
    public Result<String> updateLessonRecord (
            @RequestBody LessonRecord lessonRecord
    ){

        Date date = lessonRecord.getDate();
        String date1 = commonUtils.mySqlDateFormatDateDashToString(date);
        String subject = lessonRecord.getSubject();
        String time = lessonRecord.getTime();
        String teacherId = lessonRecord.getTeacher();
        lessonRecordService.updateTeacher(date1,subject,time,teacherId);
        return Result.ok("数据更新成功！，请留意新的课表！");
    }

    @PostMapping("startPaike")
    public Result<String> startPaike (HttpServletResponse  response,@RequestBody PaiKeVo paiKeVo){
        Date date = paiKeVo.getDate();
        String model = paiKeVo.getModel();
        List<String> teachers = paiKeVo.getTeacher();
        String time = paiKeVo.getTime();
        String remark = paiKeVo.getRemark();
        String workingDir = System.getProperty("user.dir");
        String savePath = workingDir+"/src/main/java/com/wuwei/aliocr/static/temp.xlsx";
        lessonRecordService.startPaike(model,teachers,date,time,savePath,remark);
        // 设置响应的内容类型为 Excel
        response.setContentType("application/vnd.ms-excel");

        // 设置响应头，告诉浏览器该文件以附件形式下载
        response.setHeader("Content-Disposition", "attachment; filename=\"work5.xlsx\"");

        try (InputStream inputStream = new FileInputStream(savePath);
             OutputStream outputStream = response.getOutputStream()) {
            // 将 Excel 文件的内容以流的形式写入响应对象
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return Result.ok("");
        } catch (IOException e) {
            String message = e.getMessage();
            return Result.fail(message);

        }
    }

}
